" .vimrc of Bart Trojanowski
"
" You can get a more upto date version from
"   http://www.jukie.net/~bart/conf/vimrc
"
" Most files sourced by this vimrc are located here:
"   http://www.jukie.net/~bart/conf/vim/
"
" this script is in Latin1 even when 'encoding' is UTF-8
scriptencoding latin1

" I think the following two were fixed by patches 6.0.064 and 7.1b.002 (or some such)
" I leave them in in case I happened to run an unfixed Vim
" I don't think they can hurt
if &mm < 256
        set mm=20000000
endif
if &mmt < 256
        set mmt=20000000
endif

" set menus & messages to English even on a multilingual Vim run on a non-English locale
if has("multi_lang")
        if has("unix")
                language messages C
        else
                language messages en
        endif
        language time en_GB
endif

if 1    " expression evaluation compiled-in
        runtime! menu.vim
endif

" use 256 colors in Console mode if we think the terminal supports it
if &term =~? 'mlterm\|xterm'
        let &t_Co = 256
endif

" the example vimrc sets a lot of useful settings
" ... and a few that we don't want
"runtime! vimrc_example.vim
" unmap! <C-U>
" the example vimrc doesn't set syntax highlighting on mono terminals --
" let's correct that
if has('syntax') && !(exists('syntax_on') && syntax_on)
        syntax on
endif

set nocp
" set my own color scheme
if has('autocmd') && has('syntax')
        color almost-default
        let my_colors_name = "almost-default"
endif

" ---------------------------------------------------------------------------
" first the disabled features due to security concerns
set modelines=0         " no modelines [http://www.guninski.com/vim1.html]
"let g:secure_modelines_verbose=1 " securemodelines vimscript

" ---------------------------------------------------------------------------
" configure other scripts

let c_no_curly_error = 1

" ---------------------------------------------------------------------------
" operational settings
set nocompatible                " vim defaults, not vi!
syntax on                       " syntax on
set hidden                      " allow editing multiple unsaved buffers
set more                        " the 'more' prompt
filetype on                     " automatic file type detection
filetype plugin on
set autoread                    " watch for file changes by other programs
set visualbell                  " visual beep
" set backup                      " produce *~ backup files
" set backupext=~                 " add ~ to the end of backup files
":set patchmode=~                " only produce *~ if not there
set noautowrite                 " don't automatically write on :next, etc
let maplocalleader=','          " all my macros start with ,
set wildmenu                    " : menu has tab completion, etc
set scrolloff=5                 " keep at least 5 lines above/below cursor
set sidescrolloff=5             " keep at least 5 columns left/right of cursor
set history=200                 " remember the last 200 commands

" ---------------------------------------------------------------------------
" meta
map <LocalLeader>ce :edit ~/.vimrc<cr>          " quickly edit this file
map <LocalLeader>cs :source ~/.vimrc<cr>        " quickly source this file

" ---------------------------------------------------------------------------
" window spacing
set cmdheight=2                 " make command line two lines high
set ruler                       " show the line number on bar
set lazyredraw                  " don't redraw when running macros
"set number                      " show line number on each line
"set winheight=999               " maximize split windows
"set winminheight=0              " completely hide other windws

map <LocalLeader>w+ 100<C-w>+  " grow by 100
map <LocalLeader>w- 100<C-w>-  " shrink by 100

" ---------------------------------------------------------------------------
" mouse settings
" set mouse=a                     " mouse support in all modes
set mousehide                   " hide the mouse when typing text

" ,p and shift-insert will paste the X buffer, even on the command line
nmap <LocalLeader>p i<S-MiddleMouse><ESC>
imap <S-Insert> <S-MiddleMouse>
cmap <S-Insert> <S-MiddleMouse>

" this makes the mouse paste a block of text without formatting it 
" (good for code)
map <MouseMiddle> <esc>"*p

" ---------------------------------------------------------------------------
" global editing settings
set autoindent smartindent      " turn on auto/smart indenting
set expandtab                   " use spaces, not tabs
set smarttab                    " make <tab> and <backspace> smarter
set tabstop=8                   " tabstops of 8
set shiftwidth=8                " indents of 8
set backspace=eol,start,indent  " allow backspacing over indent, eol, & start
set undolevels=1000             " number of forgivable mistakes
set updatecount=100             " write swap file to disk every 100 chars
set complete=.,w,b,u,U,t,i,d    " do lots of scanning on tab completion
set viminfo=%100,'100,/100,h,\"500,:100,n~/.viminfo

" ---------------------------------------------------------------------------
" searching...
set hlsearch                   " enable search highlight globally
set incsearch                  " show matches as soon as possible
set showmatch                  " show matching brackets when typing
" disable last one highlight
nmap <LocalLeader>nh :nohlsearch<cr>

set diffopt=filler,iwhite       " ignore all whitespace and sync

" ---------------------------------------------------------------------------
" spelling...
if v:version >= 700
  let b:lastspelllang='en'
  function! ToggleSpell()
    if &spell == 1
      let b:lastspelllang=&spelllang
      setlocal spell!
    elseif b:lastspelllang
      setlocal spell spelllang=b:lastspelllang
    else
      setlocal spell spelllang=en
    endif
  endfunction
  endif
" (try to) detect whether we have clipboard and X
if has('gui_running')
        function! TestForX1()
                return 1
        endfunction
elseif has('clipboard')
        function! TestForX()
                let @+ = " "
                let x = @+
                let @+ = '--' . x
                redir @"
                silent reg
                redir END
                let @+ = x
        "       unlet x
                return (@" =~ '\n"+ ')
        endfunction
else
        function! TestForX()
                return 0
        endfunction
endif

  nmap <LocalLeader>ss :call ToggleSpell()<CR>
if has("autocmd")
        " remove the 'textwidth' setting set by vimrc_example.vim on text files
        ""au! vimrcEx FileType text

        " define a few additional autocommands
        augroup vimrclocal

        " complete the try-to-detect-Xwindows started earlier
        " "au VimEnter *
                ""\   let clipboard_present = TestForX()
                ""\ | let X_available = has('x11') && clipboard_present

        " this one is unnecessary on recent Vim versions
        au FileType *.* exe substitute(expand('<amatch>'), '^\(.*\)\.\(.*\)$', 'doau Filetype \1 | doau Filetype \2', '')

        " remove filetype-indenting autocommands set by the vimrc_example.vim
        filetype indent off

        " set verbosity to at least 1, except during startup and closedown
        if ! &verbose
                au vimEnter * set verbose=1
                au vimLeave * set verbose=0
        endif
  setlocal spell spelllang=en
  setlocal nospell
endif
        " close all cscope connections (if any) at closedown
        if has('cscope')
                au vimLeave * cs kill -1
        endif
" ---------------------------------------------------------------------------
" some useful mappings
        " use matchit correctly on C (etc.) sources
        au Filetype c,cpp,css,javascript
        \ let b:match_words = &matchpairs

        " this was fixed by patch 7.1.261 but doesn't hurt,
        " and will make Vim open UTF-16 files with BOM correctly even without that patch
        if has('multi_byte')
                au BufReadPost * if (&fenc == 'ucs-2le') && &bomb | e ++enc=utf-16le | endif
                au BufReadPost * if (&fenc == 'ucs-2')   && &bomb | e ++enc=utf-16   | endif
        endif
" disable search complete
let loaded_search_complete = 1
if has("gui_running")
        " set the GUI font, using the correct format for the build we're on
        if has("gui_gtk2")
                set gfn=Bitstream\ Vera\ Sans\ Mono\ 8
                let s:pfn = 'Bitstream\ Vera Sans Mono'
        "       set gfn=Monaco\ 7
        "       let s:pfn='Monaco'
        elseif has("gui_photon")
                set gfn=Bitstream\ Vera\ Sans\ Mono:s8
                let s:pfn = 'Bitstream\ Vera Sans Mono'
        "       set gfn=Monaco=s7
        "       let s:pfn='Monaco'
        elseif has("gui_kde")
                set gfn=Bitstream\ Vera\ Sans\ Mono/8/-1/5/50/0/0/0/1/0
                let s:pfn = 'Bitstream\ Vera Sans Mono'
        "       set gfn=Monaco/7/-1/5/50/0/0/0/1/0
        "       let s:pfn='Monaco'
        elseif has("x11")
                set gfn=-*-lucidatypewriter-medium-r-normal-*-*-90-*-*-m-*-*
                let s:pfn = 'Lucida'
        else
                set gfn=Lucida_Console:h9:cDEFAULT
                let s:pfn = 'Lucida Console'
        endif
endif
" Y yanks from cursor to $
map Y y$
" toggle list mode
nmap <LocalLeader>tl :set list!<cr>
" toggle paste mode
nmap <LocalLeader>pp :set paste!<cr>
" change directory to that of current file
nmap <LocalLeader>cd :cd%:p:h<cr>
" change local directory to that of current file
nmap <LocalLeader>lcd :lcd%:p:h<cr>

" word swapping
nmap <silent> gw "_yiw:s/\(\%#\w\+\)\(\W\+\)\(\w\+\)/\3\2\1/<cr><c-o><c-l>
" char swapping
nmap <silent> gc xph

" save and build
nmap <LocalLeader>wm  :w<cr>:make<cr>

" this is for the find function plugin
nmap <LocalLeader>ff :let name = FunctionName()<CR> :echo name<CR> 

" http://www.vim.org/tips/tip.php?tip_id=1022
"set foldmethod=expr 
"set foldexpr=getline(v:lnum)!~\"regex\" 

" ---------------------------------------------------------------------------
"  buffer management, note 'set hidden' above

" Move to next buffer
map <LocalLeader>bn :bn<cr>
" Move to previous buffer
map <LocalLeader>bp :bp<cr>
" List open buffers
map <LocalLeader>bb :ls<cr>

" ---------------------------------------------------------------------------
" when switching buffers, preserve window view

" function! MyWinSaveView()
"         if &diff 
"                 let b:winview = winsaveview()
"         endif
" endf
" function! MyWinRestoreView()
"         if &diff 
"                 if(exists('b:winview'))
"                         call winrestview(b:winview)
"                 endif
"         endif
" endf
"
" if v:version >= 700
"         au BufLeave * :call MyWinSaveView()
"         au BufEnter * :call MyWinRestoreView()
" endif 

" ---------------------------------------------------------------------------
" dealing with merge conflicts

" find merge conflict markers
:map <LocalLeader>fc /\v^[<=>]{7}( .*\|$)<CR>


" ---------------------------------------------------------------------------

function! OnlineDoc() 
        let s:browser = "firefox"
        let s:wordUnderCursor = expand("<cword>") 

        if &ft == "cpp" || &ft == "c" || &ft == "ruby" || &ft == "php" || &ft == "python" 
                let s:url = "http://www.google.com/codesearch?q=".s:wordUnderCursor."+lang:".&ft
        elseif &ft == "vim"
                let s:url = "http://www.google.com/codesearch?q=".s:wordUnderCursor
        else 
                return 
        endif 

        let s:cmd = "silent !" . s:browser . " " . s:url 
        "echo  s:cmd 
        execute  s:cmd 
        redraw!
endfunction 
        " set GUI cursor shape
        set guicursor=n-v-c:block-Cursor/lCursor,ve:ver35-Cursor,o:hor50-Cursor
        set guicursor+=i-ci:ver25-Cursor/lCursor,r-cr:hor20-Cursor/lCursor
        set guicursor+=sm:block-Cursor,a:blinkwait750-blinkoff750-blinkon750

" online doc search 
map <LocalLeader>k :call OnlineDoc()<CR>
        " maximize the Vim GUI
        "set lines=99999 columns=99999

" ---------------------------------------------------------------------------
" status line 
function! VarExists(var, val)
    if exists(a:var) | return a:val | else | return '' | endif
endfunction
" autocmd BufEnter *gz let b:gzflag=1
set laststatus=2
if has('statusline')
        " Status line detail: (from Rafael Garcia-Suarez)
        " %f		file path
        " %y		file type between braces (if defined)
        " %([%R%M]%)	read-only, modified and modifiable flags between braces
        " %{'!'[&ff=='default_file_format']}
        "			shows a '!' if the file format is not the platform
        "			default
        " %{'$'[!&list]}	shows a '*' if in list mode
        " %{'~'[&pm=='']}	shows a '~' if in patchmode
        " (%{synIDattr(synID(line('.'),col('.'),0),'name')})
        "			only for debug : display the current syntax item name
        " %=		right-align following items
        " #%n		buffer number
        " %l/%L,%c%V	line number, total number of lines, and column number
        " "function! SetStatusLineStyle()
                        " let &stl="%f %y%([%R%M]%)%{'!'[&ff=='".&ff."']}%{'$'[!&list]}" .
                                                " \"%{'~'[&pm=='']}"                     .
                                                " \"%=#%n %l/%L,%c%V "                   .
                                                " \"[aka] %F ByteOffset %O"
                        " let &statusline="[aka]%<%f%h%m%r%=%b\ 0x%B\ \ %l,%c%V\ %P %r%{VarExists('b:gzflag','\ [GZ]')}%y%h"

                        

        ""endfunc
        "call SetStatusLineStyle()

        "function! SetStatusLineStyle()
               "let &stl="%f %y "                       .
              ""         \"%([%R%M]%)"                   .
              ""          \"%#StatusLineNC#%{&ff=='unix'?'':&ff.'\ format'}%*" .
               ""         \"%{'$'[!&list]}"               .
                ""        \"%{'~'[&pm=='']}"              .
                 ""       \"%="                           .
                  ""      \"%#StatusLineNC#%{GitBranch()}%* " .
                   ""     \"#%n %l/%L,%c%V "              .
                    ""    \""
                 "      \"%#StatusLineNC#%{GitBranchInfoString()}%* " .
        ""endfunc
        ""call SetStatusLineStyle()
        set keywordprg=MANPAGER=more\ man\ -a\  " command to be used for the K command
endif
if &term == "mlterm"        " the true-bidi terminal
                let &t_kb = "\x7F"      " termcap patch for mlterm backspace key
endif

" ---------------------------------------------------------------------------
" setup for the visual environment
if has('gui_running')
        set bg=light
        set guioptions-=T
        set guioptions+=m " Add menu bar
        set guioptions+=c
        "set guifont=-schumacher-clean-medium-r-normal-*-*-120-*-*-c-*-iso646.1991-irv
        "set guifont=Monospace\ 8,Terminal\ 8,fixed
        " set guifont=ProggyCleanTT\ 12
endif

if $TERM =~ '^xterm'
        set t_Co=256 
elseif $TERM =~ '^screen-bce'
        set t_Co=256            " just guessing
elseif $TERM =~ '^rxvt'
        set t_Co=88
elseif $TERM =~ '^linux'
        set t_Co=8
else
        set t_Co=16
endif

" let g:inkpot_black_background = 1
" colorscheme wombat
colorscheme winter

" ---------------------------------------------------------------------------
" Folding for unified diffs 
" http://pastey.net/1483, mgedmin on #vim

function! DiffFoldLevel(lineno) 
        let line = getline(a:lineno) 
        if line =~ '^Index:' 
                return '>1' 
        elseif line =~ '^===' || line =~ '^RCS file: ' || line =~ '^retrieving revision '
                let lvl = foldlevel(a:lineno - 1) 
                return lvl >= 0 ? lvl : '=' 
        elseif line =~ '^diff' 
                return getline(a:lineno - 1) =~ '^retrieving revision ' ? '=' : '>1' 
        elseif line =~ '^--- ' && getline(a:lineno - 1) !~ '^diff\|^===' 
                return '>1' 
        elseif line =~ '^@' 
                return '>2' 
        elseif line =~ '^[- +\\]' 
                let lvl = foldlevel(a:lineno - 1) 
                return lvl >= 0 ? lvl : '=' 
        else 
                return '0' 
        endif 
endf

function! FT_Diff() 
        if v:version >= 600 
                setlocal foldmethod=expr 
                setlocal foldexpr=DiffFoldLevel(v:lnum) 
        endif 
endf 
 
" ---------------------------------------------------------------------------
" no folds in vimdiff

function! NoFoldsInDiffMode()
        if &diff 
                :silent! :%foldopen! 
        " some more Console-mode-only settings
        set keywordprg=man
        set title titleold= titlestring=%t\ -\ VIM
  
        " change cursor color for Insert (commented out, doesn't work for me)
        endif
        if &term == 'xterm' && 0
                let &t_SI = "\e]12;CursorShape=1\x07"
                let &t_EI = "\e]50;CursorShape=0\x07"
        endif
endf

augroup Diffs 
  autocmd! 
  autocmd BufRead,BufNewFile *.patch :setf diff 
  autocmd BufEnter           *       :call NoFoldsInDiffMode()
  autocmd FileType           diff    :call FT_Diff() 
augroup END

" override previous 'keywordprg' settings if not on Unix
if !has('unix')
        set keywordprg=:help
endif


" ---------------------------------------------------------------------------
" tabs
map <LocalLeader>tc :tabnew %<cr>    " create a new tab       
map <LocalLeader>td :tabclose<cr>    " close a tab
map <LocalLeader>tn :tabnext<cr>     " next tab
map <LocalLeader>tp :tabprev<cr>     " previous tab
map <LocalLeader>tm :tabmove         " move a tab to a new location

" "dcraven" pasted "TabMessage: Put output of ex commands in a new tab." 
" (10 lines, 287B) at http://sial.org/pbot/20504

"TabMessage: Put output of ex commands in a new tab.
function! TabMessage(cmd)
        redir => message
        silent execute a:cmd
        redir END
        tabnew
        silent put=message
        set nomodified
endfunction
command! -nargs=+ -complete=command TabMessage call TabMessage(<q-args>)

" ---------------------------------------------------------------------------
" auto load extensions for different file types
if has('autocmd')
        filetype plugin indent on
        syntax on

        " jump to last line edited in a given file (based on .viminfo)
        "autocmd BufReadPost *
        "       \ if !&diff && line("'\"") > 0 && line("'\"") <= line("$") |
        "       \       exe "normal g`\"" |
        "       \ endif
        autocmd BufReadPost *
                \ if line("'\"") > 0|
                \       if line("'\"") <= line("$")|
                \               exe("norm '\"")|
                \       else|
                \               exe "norm $"|
                \       endif|
                \ endif

        " improve legibility
        au BufRead quickfix setlocal nobuflisted wrap number

        " configure various extenssions
        let git_diff_spawn_mode=2

        " improved formatting for markdown
        " http://plasticboy.com/markdown-vim-mode/
        autocmd BufRead *.mkd  set ai formatoptions=tcroqn2 comments=n:>
        autocmd BufRead ~/.blog/entries/*  set ai formatoptions=tcroqn2 comments=n:>
endif
" switch to UTF-8 if possible (and not already done by the OS)
if has("multi_byte")
        let g:locale_encoding = &encoding
        if &encoding !~? '^u'           " ... if not already Unicode ...
                if &termencoding == ""
                        let &termencoding = &encoding
                endif
                set encoding=utf-8
        endif
        set fileencodings=ucs-bom,utf-8,latin1
        setg bomb fileencoding=utf-8
"       if has("printer")
"               set penc=utf-8
"       endif
endif
" ---------------------------------------------------------------------------
"import other files...
":source ~/.vim/bk.vim      " does anyone actualy use bk anymore?

let $kernel_version=system('uname -r | tr -d "\n"')
set tags=./tags,tags,../tags,../../tags,../../../tags,../../../../tags,/lib/modules/$kernel_version/build/tags,/usr/include/tags

helptags ~/.vim/doc

set dictionary=/usr/share/dict/words            " used with CTRL-X CTRL-K

" ---------------------------------------------------------------------------
"run the import script that looks for localized configuration changes
" source ~/.vim/localized_vimrc.vim

" ---------------------------------------------------------------------------
"configure other scripts

" enable autoinstall of scripts w/o markup
" see :h :GLVS
let g:GetLatestVimScripts_allowautoinstall=1

" dynamic-explorer.vim (script 1890)
nmap <silent> <LocalLeader>f :FilesystemExplorer<CR>
nmap <silent> <LocalLeader>b :BufferExplorer<CR>

" ---------------------------------------------------------------------------
"this is for hg menu
if filereadable( "/usr/share/doc/mercurial/examples/hg-menu.vim" )
        let $backup_mapleader=mapleader
        let mapleader = ","
        source /usr/share/doc/mercurial/examples/hg-menu.vim
        let mapleader = $backup_mapleader
" additional options
set autowriteall                        " save (if possible) when |abandon|ing a file
" set backup                              " back up old versions
" if has('writebackup')                   " but only if not equipped with the more advanced 'writebackup'
  ""      set nobackup writebackup
endif

" indent settings (we do NOT want filetype-related indent)
set autoindent
if has('smartindent')
        set smartindent
endif

set errorbells visualbell                       " use both audio and visual bell
if 1                    " has arithmetic evaluation
        let &t_vb = "\x07" . &t_vb              " 07 is the BEL character, rings the terminal bell
endif
if has('autocmd') && has('gui')
        " must set it again for the GUI
        au GUIEnter * let &t_vb = "\<C-G>\e|50f"
        " where 50 is the flash time in milliseconds
endif

if exists("+modelines")
        " the following is required because of SuSE's paranoid /etc/vimrc
        " and to force 'modeline' on even for root in Vim 7.0.237 and later
        set modeline modelines=5
        " the following disables a dangerous modeline in one helpfile
        if has ('autocmd')
                au BufReadPost ada.txt setl nomodeline ft=help
        endif
endif

set report=0            " report # of :substitute changes even if only one
set nojoinspaces        " don't use double spaces (e.g. after periods) when joining
set selection=inclusive keymodel=startsel selectmode=key        " :behave tonymec       ;-)
set laststatus=2        " always display bottom status line
set display=lastline    " if the last line (with 'wrap') overshoots the window bottom,
                        " display as much of it as possible
set timeout timeoutlen=5000 ttimeoutlen=100     " timeouts: 0.1s on keycodes, 5s on mappings
set scrolloff=3         " display at least 3 lines of context above & below cursor if possible
set nrformats=          " have ^A and ^X increment/decrement only in decimal
set formatoptions-=c    " autowrap comments using textwidth
set tags=tags,./tags    " ignore emacs-style tagfiles by default

" set 'list' and 'listchars' options
""set list listchars=eol:$                " $ should work on all 8-byte encodings
" "if has('multi_byte')
          ""set listchars+=eol:EOF             " on multibyte Vim (where 'encoding'  is UTF-8)
                                        " we can use the prettier Pilcrow mark
""endif
set listchars+=tab:\|_                  " show tabs as |_______|_______
silent! set listchars+=nbsp:~           " show no-break space as tilde if supported
" silent! set listchars+=precedes:<,extends:>

set ignorecase smartcase        " ignore case when search text is all-lowercase

" case adjust in Insert completion
if exists("+infercase")
        set infercase
endif

" add atsign to 'isfname' characters
set isfname+=@-@

" path search settings
if has('file_in_path')
        set path=.,,
        if has('path_extra')
                set path^=$HOME/**
        else
                set path^=$HOME
        endif
endif

set whichwrap=<,>,[,],~,s       " allow line-wrapping on <Left> <Right> <Space> and tilde

""if has("mouse")
        ""set mouse=a mousemodel=popup selectmode+=mouse
""endif

" if exists("+cursorcolumn")
         ""set cuc cul
""endif

if has("diff")
        set diffopt+=context:0
endif

if exists("+imsearch")
        setg ims=-1     " set 'imsearch' to mimic 'iminsert' by default
endif

" set up Rolodex Vim
if has("windows")
    if has("autocmd")
      augroup rolodex
        au VimEnter * set noea wmh=0 wh=99999 hh=99999 cwh=99999
      augroup vimrclocal
    else
        set noea wmh=0 wh=99999 hh=99999 cwh=99999
    endif
endif

" display up to 4 combining chars merged with a given spacing char
if exists("+maxcombine")
        set mco=4
endif

" allow removing combining chars one-by-one
if exists("+delcombine")
        set deco
endif

" set 'wildmenu' option, to get completion-by-menu (on the status line when hitting Tab)
if has("wildmenu")
        set wildmenu wildmode=longest:full,full
else
        set wildmode=longest,list:longest,full
endif

if has("wildignore")
        set wildoptions=tagfile         " display tag kind if possible
endif

if exists("+clipboard")
        set clipboard=exclude:cons\\\|linux
        if has('multi_byte') && has('gui_gtk2') && (((version == 702) && has('patch201')) || (version > 702))
                set clipboard^=html
        endif
endif

if has('cscope')
        set cst csverb 
        if has('quickfix')
                set csqf=s-,c-,d-,i-,t-,e-
        endif
        if version < 700
                cnoreabbrev csf cs find
                cnoreabbrev csk cs kill
                cnoreabbrev css cs show
                cnoreabbrev csh cs help
        else
                cnoreabbrev <expr> csa ((getcmdtype() == ':' && getcmdpos() <= 4)? 'cs add'  : 'csa')
                cnoreabbrev <expr> csf ((getcmdtype() == ':' && getcmdpos() <= 4)? 'cs find' : 'csf')
                cnoreabbrev <expr> csk ((getcmdtype() == ':' && getcmdpos() <= 4)? 'cs kill' : 'csk')
                cnoreabbrev <expr> css ((getcmdtype() == ':' && getcmdpos() <= 4)? 'cs show' : 'css')
                cnoreabbrev <expr> csh ((getcmdtype() == ':' && getcmdpos() <= 4)? 'cs help' : 'csh')
        endif
endif

if exists("+guioptions")
        set go-=a go-=e go+=tc
        " remove a      no autoselect to * register
        " remove e      always use text-style tabs
        " add    t      include tearoff menu items if possible
        " add    c      avoid popup dialogs for small choices
endif

if exists("+guiheadroom")
        set ghr=0
endif

" define our text-style tabline
" this is adapted (with some enhancements) from the example at :help setting-tabline
if exists("+showtabline")
        function! MyTabLine()
                let s = ''
                let t = tabpagenr()
                let i = 1
                while i <= tabpagenr('$')
                        let buflist = tabpagebuflist(i)
                        let winnr = tabpagewinnr(i)
                        let s .= '%' . i . 'T'
                        let s .= (i == t ? '%1*' : '%2*')
                        let s .= ' '
                        let s .= i . ':'
                        let s .= winnr . '/' . tabpagewinnr(i,'$')
                        let s .= ' %*'
                        let s .= (i == t ? '%#TabLineSel#' : '%#TabLine#')
                        let file = bufname(buflist[winnr - 1])
                        let file = fnamemodify(file, ':p:t')
                        if file == ''
                                let file = '[No Name]'
                        endif
                        let s .= file
                        let i = i + 1
                endwhile
                let s .= '%T%#TabLineFill#%='
                let s .= (tabpagenr('$') > 1 ? '%999XX' : 'X')
                return s
        endfunction
        set stal=2
        set tabline=%!MyTabLine()
"       map     <F10>   :tabnext<CR>
"       map!    <F10>   <C-O>:tabnext<CR>
"       map     <S-F10> :tabprev<CR>
"       map!    <S-F10> <C-O>:tabprev<CR>
endif

" when splitting, put new window after current by default
if exists("+splitbelow")
        set splitbelow
endif
if exists("+splitright")
        set splitright
endif

" avoid too-frequent "more?" prompts
if &cmdheight < 2
        set cmdheight=2
endif

" custom status line, see :help 'statusline' for details
" if has("statusline")
        "set statusline=%<%f\ %h%m%r%=%k[%{(&fenc\ ==\ \"\"?&enc:&fenc).(&bomb?\",BOM\":\"\")}][U+%04B]\ %-12.(%l,%c%V%)\ %P
"endif

" session options
if has('mksession')
        set ssop-=curdir ssop+=sesdir,globals,localoptions
endif

" highlight syntax all the way, even on very long lines
if exists("+synmaxcol")
        set synmaxcol=0
endif

if exists("+completeopt")
        set completeopt=menuone,preview
endif

" ===========================================================================
" history and viminfo options
set history=200
if has('viminfo')
        set vi-=h vi+=!,%
        if has("unix")
                set vi+=r/media/dvdrecorder,r/mnt/floppy
        else
                set vi+=ra:,rb:
        endif
endif

if 1                    " only if has arithmetic evaluation
        " netrw settings
        let netrw_alto          = 1
        let netrw_altv          = 1
        let netrw_liststyle     = 1
        " let netrw_keepdir     = 0
        let netrw_longlist      = 1
        let netrw_mousemaps     = 0
        let netrw_noretmap      = 1     " disable going back by double clicking
        let netrw_timefmt       = '%a %d %b %Y %T'

        " syntax settings for shell syntax
        let is_bash             = 1 " our 'sh' Bourne shell is alias to bash
        let sh_fold_enabled     = 7 " enable all kinds of syntax folding
endif

" Mappings and abbreviations

" make Ctrl-arrows move by words not WORDS
" (like they already do in Insert mode).
map     <C-Left>        b
map     <C-Right>       w

if exists('+iminsert')
        " map F8 to toggle keymap (Ctrl-^ not present on keyboard)
        noremap  <F8> :let &l:iminsert = ! &l:iminsert<CR>
        lnoremap <F8> <C-O>:let &l:iminsert = ! &l:iminsert<CR>
        noremap! <F8> <C-O>:let &l:iminsert = ! &l:iminsert<CR>
        cnoremap <F8> <C-^>
endif

" ---------------------------------------------------------------------------
"  configure calendar
let g:calendar_monday = 1
" unmap ZZ (exit). We have :qa anyway.
map ZZ <Nop>
set nobackup
let g:miniBufExplMapWindowNavVim = 1
let g:miniBufExplMapWindowNavArrows = 1
let g:miniBufExplMapCTabSwitchBufs = 1
let g:miniBufExplModSelTarget = 1 
let g:is_bash=1
let g:sh_fold_enabled= 3
autocmd BufEnter *.sh :set foldmethod=syntax
autocmd BufEnter *.sh :colorscheme tomatosoup
let g:SuperTabDefaultCompletionType = "context"
let g:SuperTabCompletionContexts = ['s:ContextText', 's:ContextDiscover']
let g:SuperTabContextTextOmniPrecedence = ['&omnifunc', '&completefunc']
let g:SuperTabContextDiscoverDiscovery =
    \ ["&completefunc:<c-x><c-u>", "&omnifunc:<c-x><c-o>"]
set wildcharm=<C-T>             " or any key not needed in Command-line mode
if has('menu')
        " override Ctrl-Z (minimize) by a text-mode menu
        map <C-Z> :emenu <C-T>
        imap <C-Z> <C-O>:emenu <C-T>
endif
" F9            follow help link
map     <F9>    <C-]>
" F9            terminate abbreviation
map!    <F9>    <C-]>
" F11           go to next window
" Shift-F11     go to previous window
" (with count) F11 or Shift-F11 both go to nth window
map     <F11>   <C-W>w
map!    <F11>   <C-O><C-W>w
map     <S-F11> <C-W>W
map!    <S-F11> <C-O><C-W>W
" move current window up and down
noremap <C-W>X  <C-W>W<C-W>x
noremap <C-W>x  <C-W>x<C-W>w
" F2            go to next quickfix line
" Shift-F2      go to previous quickfix line
map     <F2>    :cnext<CR>zv
map     <S-F2>  :cprev<CR>zv
" F4            paste clipboard after last line
" Shift-F4      paste clipboard before 1st line
" omitted if clipboard is inaccessible or not compiled-in
" "if has('autocmd')
        ""au VimEnter *
                ""\ if clipboard_present
                        ""\ | exe 'map    <F4>    :$put +<CR>'
                        ""\ | exe 'map    <S-F4>  :0put +<CR>'
                        ""\ | exe 'imap   <F4>    <C-O>:$put +<CR>'
                        ""\ | exe 'imap   <S-F4>  <C-O>:0put +<CR>'
                ""\ | endif
""endif
" F3            save our work
map     <F3>    :wa<Bar>wv<CR>
imap    <F3>    <C-O>:wa<Bar>wv<CR>
map     <S-F3>  8<Bar>v/\.<CR>hy/\/<C-R>"\.<CR>
imap    <S-F3>  <Esc>8<Bar>v/\.<CR>hy/\/<C-R>"<CR>a
if 1
        function! Fortune()
                " In order to remember them in the viminfo,
                " the first two variables defined below
                " must have names starting with an uppercase letter
                " and containing no lowercase letters.
                if !exists("g:FORTUNE")
                        let g:FORTUNE = 0
                endif
                if !exists("g:FORTUNECYCLE")
                        let g:FORTUNECYCLE = 5
                endif
                if !exists("s:sysFortunes")
                        let s:sysFortunes =
                        \ (system("which fortune") != "") && (!v:shell_error)
                endif
                if !exists("s:bramFortunes")
                        let s:bramFortunes =
                        \ filereadable(expand("~/fortunes.txt"))
                endif
                if s:sysFortunes && (g:FORTUNE || (!s:bramFortunes))
                        let @+ = "-- \n" . system("fortune -a")
                elseif s:bramFortunes
                        new ~/fortunes.txt
                        silent 1;/^-- $/-1d +
                        $put +
                        wq
                else
                        let @+ = ""
                endif
                let g:FORTUNE = g:FORTUNE + 1
                if g:FORTUNE >= g:FORTUNECYCLE
                        let g:FORTUNE = 0
                endif
                return @+
        endfunction
map <F5> :echo Fortune()<CR>
endif
"
" Up, Down      move up/down by "screen lines"
" j k           (default) move down/up by "file lines"
map     <Down>  gj
map     <Up>    gk
" if exists("*pumvisible")
"       inoremap <expr> <Down>  pumvisible() ? "\<lt>Down>" : "\<lt>C-O>gj"
"       inoremap <expr> <Up>    pumvisible() ? "\<lt>Up>"   : "\<lt>C-O>gk"
" else
"       inoremap        <Down>  <C-O>gj
"       inoremap        <Up>    <C-O>gk
"endif

" scroll mouse by single lines
if has('mouse')
        noremap         <MouseUp>       <C-E>
        inoremap        <MouseUp>       <C-O><C-E>
        noremap         <MouseDown>     <C-Y>
        inoremap        <MouseDown>     <C-O><C-Y>
endif

set expandtab
set shiftwidth=2
set softtabstop=2
if has("autocmd")
  " Enable file type detection.
  " Use the default filetype settings, so that mail gets 'tw' set to 72,
  " 'cindent' is on in C files, etc.
  " Also load indent files, to automatically do language-dependent indenting.
  filetype plugin indent on
  " ...
endif
" make left-arrow work over indent/eol/start
noremap <Left>  <BS>
" open help window at bottom unless :help typed in full
if version < 700
        cnoreabbrev     h       bot h
else
        cnoreabbrev     <expr>  h       ((getcmdtype() == ':' && getcmdpos() <= 2)? 'bot h' : 'h')
endif
map     <F1>    :bot help<CR>
" map Ctrl-L to invoke :diffupdate when in diff mode (disabled)
" if has("diff")
"       map     <C-L>   :if &diff <Bar> diffu <Bar> else <Bar> redraw <Bar> endif <CR>
"       imap    <C-L>   <C-O>:if &diff <Bar> diffu <Bar> else <Bar> redraw <Bar> endif <CR>
" endif

" Ctrl-K comma colon (in Insert mode): UTF-8 single-codepoint ellipsis "..."
" disregard error if (for instance) not in UTF-8
if has("digraphs")
        silent! dig     ,:      8230            " HORIZONTAL ELLIPSIS
endif

if has('insert_expand')
        " mappings for «ordinary» Insert-mode completion
        inoremap        <F12>           <C-X><C-N>
        inoremap        <S-F12>         <C-X><C-P>
        " mapping for Omni completion
        inoremap        <F6>            <C-X><C-O>
endif

" repeat latest substitute
map     µ       :&&<CR>
" find non-UTF8 in 8-bit files
map     £       8g8

" the following are to force-break autocomplete on these keys
inoremap        <C-Y>   <Space><BS><C-Y>
inoremap        <C-E>   <Space><BS><C-E>
" Add some undo points in Insert mode
if (version > 602) || ((version == 602) && has("patch148"))     " <C-G>u sets undo point
        inoremap        <CR>    <C-G>u<CR>
else
        inoremap        <CR>    <C-O>o
endif
inoremap        <Space>         <Space><Left><Right>

if has("user_commands")
        command! -nargs=0 -bar WhatSyntax echomsg synIDattr(synID(line("."),col("."),0),"name") synIDattr(synIDtrans(synID(line("."),col("."),0)),"name") synIDattr(synID(line("."),col("."),1),"name") synIDattr(synIDtrans(synID(line("."),col("."),1)),"name")
        command! -nargs=0 -bar -bang -range -reg Put exe ((<q-bang> == '!') ? <q-line1> : <q-line2>) . 'put' . <q-bang> <q-reg>
        command! -nargs=* -bar -bang -range Iline <line1>,<line2>Put<bang> =<q-args>
endif

if has('autocmd')
        augroup END
endif
" If buffer modified, update any 'Last modified: ' in the first 20 lines.
" 'Last modified: ' can have up to 10 characters before (they are retained).
" Restores cursor and window position using save_cursor variable.
function! LastModified()
  if &modified
    let save_cursor = getpos(".")
    let n = min([20, line("$")])
    keepjumps exe '1,' . n . 's#^\(.\{,20}Last modified: \).*#\1' .
          \ strftime('%a %b %d, %Y  %I:%M%p') . '#e'
    call histdel('search', -1)
    call setpos('.', save_cursor)
  endif
endfun
autocmd BufWritePre * call LastModified()
noremap ,bea :silent %!beautify_bash.py -
:nnoremap <F5> "=strftime("%c")<CR>P
:inoremap <F5> <C-R>=strftime("%c")<CR>
set mouse=
set nobackup

" Change the cursor colour"
map @1 :!echo -!= "\033]12;midnightblue\007" <CR><CR>
map @1 :!echo -!= "\033]12;grey\007" <CR><CR>
map @1 :!echo -!= "\033]12;chartreuse\007" <CR><CR>
map @1 :!echo -!= "\033]12;SlateBlue\007" <CR><CR>

" Added from vimrc_local"
let g:python_highlight_all=1
" Tab settings for filetypes that should be set even if ftplugin is off.
" Note: sr=shiftround, et=expandtab, ts=tabstop, sw=shiftwidth
set sr et ts=4 sw=4 " default
"autocmd FileType python set sr et ts=4 sw=4 " Python
autocmd FileType make set sr noexpandtab ts=8 sw=8 " Makefile
autocmd FileType man set sr noexpandtab ts=8 sw=8 " Man page (also used by psql to edit or view)
autocmd FileType calendar set sr noexpandtab ts=8 sw=8 " calendar(1) reminder service
" These are used by the DirDiff plugin.
" DirDiff rules!
let g:DirDiffExcludes = ".svn,*.jpg,*.png,*.gif,*.swp,*.a,*.so,*.o,*.pyc,*.exe,*.class,CVS,core,a.out"
let g:DirDiffIgnore = "Id:,Revision:,Date:"
" Automatically load templates for new files. Silent if the template for the
" extension does not exist. Virtually all template plugins I have seen for Vim
" are too complicated. This just loads what extension matches in
" $VIMHOME/templates/. For example the contents of html.tpl would be loaded
" for new html documents.
augroup BufNewFileFromTemplate
au!
autocmd BufNewFile * silent! 0r $HOME/.vim/templates/%:e.tpl
autocmd BufNewFile * normal! G"_dd1G
autocmd BufNewFile * silent! match Todo /TODO/
augroup BufNewFileFromTemplate
" \cwd changes current working directory
map <leader>cwd :cd %:p:h<CR>
" map Q as @q (replay the recording named q). I always use q as my throw-away
" recording name, so I start recording with "qq" then reply the recording with
" "Q". I never found a use for interactive ex-mode so I don't miss the
" original definition of Q.
nnoremap Q @q

" get rid of most annoying typo: typing q: when I meant :q.
" You can still get to cmdline-window easily by typing <Ctrl-F> in
" command mode, so loosing q: is no loss.
map q: :q

" easy indentation in visual mode
" This keeps the visual selection active after indenting.
" Usually the visual selection is lost after you indent it.
vmap > >gv
vmap < <gv
" Use display movement with arrow keys for extra precision. Arrow keys will
" move up and down the next line in the display even if the line is wrapped.
" This is useful for navigating very long lines that you often find with
" automatically generated text such as HTML.
" This is not useful if you turn off wrap.
imap <up> <C-O>gk
imap <down> <C-O>gj
nmap <up> gk
nmap <down> gj
vmap <up> gk
vmap <down> gj
" Split window selector and stacker.
" CTRL-J goes down one window and maximizes it; other windows are minimized.
" CTRL-K goes up one window and maximizes it; other windows are minimized.
map <C-J> <C-W>j<C-W>_
map <C-K> <C-W>k<C-W>_

" This maps \y so that it will yank the visual selection, but also quote the
" regex metacharacters, so you can then paste into a search pattern. For
" example, use v to select some text. Press \y. Then start a search with /.
" Type CTRL-R" to insert the yanked selection. The last two mappings allow you
" to visual select an area and then search for other matches by typing * or #.
vmap <silent> <leader>y y:let @"=substitute(escape(@",'.$*[^\/~'),'\n','\\n','g')<CR>
vmap <silent> * y:let @/=substitute(escape(@",'.$*[^\/~'),'\n','\\n','g')<CR>n
vmap <silent> # y:let @/=substitute(escape(@",'.$*[^\/~'),'\n','\\n','g')<CR>N
vnoremap <silent> * :<C-U>
              \let old_reg=getreg('"')<bar>
              \let old_regmode=getregtype('"')<cr>
              \gvy/<C-R><C-R>=substitute(substitute(
              \escape(@", '\\/.*$^~[]' ), "\n$", "", ""),
              \"\n", '\\_[[:return:]]', "g")<cr><cr>
              \:call setreg('"', old_reg, old_regmode)<cr>
vnoremap <silent> # :<C-U>
              \let old_reg=getreg('"')<bar>
              \let old_regmode=getregtype('"')<cr>
              \gvy/<C-R><C-R>=substitute(substitute(
              \escape(@", '\\/.*$^~[]' ), "\n$", "", ""),
              \"\n", '\\_[[:return:]]', "g")<cr><cr>
              \:call setreg('"', old_reg, old_regmode)<cr>
vnoremap <silent> # :<C-U>
              \let old_reg=getreg('"')<bar>
              \let old_regmode=getregtype('"')<cr>
              \gvy?<C-R><C-R>=substitute(substitute(
              \escape(@", '\\/.*$^~[]' ), "\n$", "", ""),
              \"\n", '\\_[[:return:]]', "g")<cr><cr>
              \:call setreg('"', old_reg, old_regmode)<cr>

" echo the date and time
"map <leader>d :echo strftime("%Y-%m-%d %H:%M:%S")<CR>

au BufWritePost *.sh,*.pl,*.cgi if FileExecutable("%:p") | :!chmod a+x % ^@ |endif
let g:Perl_MapLeader = ','
let g:Perl_Author='Amit Agarwal'
let g:BASH_AuthorName   = 'Amit Agarwal'
let g:BASH_AuthorRef    = 'AKA'
let g:BASH_Email        = 'amit.agarwal@amit-agarwal.co.in'
let g:BASH_Company      = 'Individual'
let g:BASH_SyntaxCheckOptionsGlob  = "-O extglob"
let g:BASH_MapLeader  = ','


ab aka Amit Agarwal

let g:C_MenuHeader             =  "yes"
let g:C_TemplateOverwrittenMsg  = 'yes'
let g:C_GuiSnippetBrowser       = 'gui'
let g:C_Printheader            =  "%<%f%h%m%<  %=%{strftime('%x %X')}     Page %N"
let g:dumbbuf_hotkey = ""


" More additions by Amit
"
"
augroup amit_ft
        autocmd!
        autocmd FileType pl :colorscheme torte
        autocmd FileType sh :colorscheme biogoo
        autocmd FileType c  :colorscheme motus
augroup END


"Added from http://www.ibm.com/developerworks/linux/library/l-vim-script-5/index.html?ca=drs-
augroup AutoMkdir
    autocmd!
    autocmd  BufNewFile  *  :call EnsureDirExists()
augroup END
function! EnsureDirExists ()
    let required_dir = expand("%:h")
    if !isdirectory(required_dir)
        call AskQuit("Directory '" . required_dir . "' doesn't exist.", "&Create it?")

        try
            call mkdir( required_dir, 'p' )
        catch
            call AskQuit("Can't create '" . required_dir . "'", "&Continue anyway?")
        endtry
    endif
endfunction

function! AskQuit (msg, proposed_action)
    if confirm(a:msg, "&Quit?\n" . a:proposed_action) == 1
        exit
    endif
endfunction

function! Highlight_cursor ()
    set cursorline
    redraw
    sleep 1
    set nocursorline
endfunction
function! Autosave ()
   if &modified && g:autosave_on_focus_change
       write
       echo "Autosaved file while you were absent"
   endif
endfunction

autocmd  FocusGained  *.txt   :call Highlight_cursor()
autocmd  FocusLost    *.txt   :call Autosave()

augroup NoSimultaneousEdits
    autocmd!
    autocmd  SwapExists  ~/*            :let v:swapchoice = 'q'
    autocmd  SwapExists  /tmp/*            :let v:swapchoice = 'o'
    autocmd  SwapExists  /dev/shared/*  :let v:swapchoice = 'o'
augroup END

augroup CodeFormatters
    autocmd!
    autocmd  BufWritePre   *.py    :silent %!PythonTidy.py 
    autocmd  BufWritePre   *.p[lm] :silent %!perltidy -q
    autocmd  BufWritePre   *.xml   :silent %!xmlpp –t –c –n
    autocmd  BufWritePre   *.[ch]  :silent %!indent
    autocmd  BufWritePre   *.sh  :silent %!beautify_bash.py -
augroup END


:set foldmethod=expr foldexpr=TimeStampFoldExpr() foldtext=TimeStampFoldText()

let g:TEMPLATE_HOME = "/home/amitag/.vim/templates"
let g:netrw_cursorline=1

""""""""""""""""""""""""""""""
" => Python section
""""""""""""""""""""""""""""""
let python_highlight_all = 1
au FileType python syn keyword pythonDecorator True None False self

au BufNewFile,BufRead *.jinja set syntax=htmljinja
au BufNewFile,BufRead *.mako set ft=mako

au FileType python inoremap <buffer> $r return
au FileType python inoremap <buffer> $i import
au FileType python inoremap <buffer> $p print
au FileType python inoremap <buffer> $f #--- PH ----------------------------------------------<esc>FP2xi
au FileType python map <buffer> <leader>1 /class
au FileType python map <buffer> <leader>2 /def
au FileType python map <buffer> <leader>C ?class
au FileType python map <buffer> <leader>D ?def


""""""""""""""""""""""""""""""
" => JavaScript section
"""""""""""""""""""""""""""""""
au FileType javascript call JavaScriptFold()
au FileType javascript setl fen
au FileType javascript setl nocindent

au FileType javascript imap <c-t> AJS.log();<esc>hi
au FileType javascript imap <c-a> alert();<esc>hi

au FileType javascript inoremap <buffer> $r return
au FileType javascript inoremap <buffer> $f //--- PH ----------------------------------------------<esc>FP2xi

function! JavaScriptFold()
    setl foldmethod=syntax
    setl foldlevelstart=1
    syn region foldBraces start=/{/ end=/}/ transparent fold keepend extend

endfunction
function! FoldText()
   return substitute(getline(v:foldstart), '{.*', '{...}', '')
endfunction
setl foldtext=FoldText()


""""""""""""""""""""""""""""""
" => MRU plugin
""""""""""""""""""""""""""""""
let MRU_Max_Entries = 400
map <leader>f :MRU<CR>


""""""""""""""""""""""""""""""
" => Command-T
""""""""""""""""""""""""""""""
let g:CommandTMaxHeight = 15
set wildignore+=*.o,*.obj,.git,*.pyc
noremap <leader>j :CommandT<cr>
noremap <leader>y :CommandTFlush<cr>


""""""""""""""""""""""""""""""
" => Vim grep
""""""""""""""""""""""""""""""
let Grep_Skip_Dirs = 'RCS CVS SCCS .svn generated'
set grepprg=/bin/grep\ -nH



"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => MISC
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Remove the Windows ^M - when the encodings gets messed up
noremap <Leader>m mmHmt:%s/<C-V><cr>//ge<cr>'tzt'm
"Quickly open a buffer for scripbble
map <leader>q :e ~/buffer<cr>
au BufRead,BufNewFile ~/buffer iab <buffer> xh1 ===========================================
map <leader>pp :setlocal paste!<cr>
map <leader>bb :cd ..<cr>
hi User1 term=inverse,bold cterm=inverse,bold ctermfg=red
set cul                                           " highlight current line
hi CursorLine term=none cterm=none ctermbg=3      " adjust color




"recalculate the trailing whitespace warning when idle, and after saving
autocmd cursorhold,bufwritepost * unlet! b:statusline_trailing_space_warning

"return '[\s]' if trailing white space is detected
"return '' otherwise
function! StatuslineTrailingSpaceWarning()
    if !exists("b:statusline_trailing_space_warning")

        if !&modifiable
            let b:statusline_trailing_space_warning = ''
            return b:statusline_trailing_space_warning
        endif

        if search('\s\+$', 'nw') != 0
            let b:statusline_trailing_space_warning = '[\s]'
        else
            let b:statusline_trailing_space_warning = ''
        endif
    endif
    return b:statusline_trailing_space_warning
endfunction


"return the syntax highlight group under the cursor ''
function! StatuslineCurrentHighlight()
    let name = synIDattr(synID(line('.'),col('.'),1),'name')
    if name == ''
        return ''
    else
        return '[' . name . ']'
    endif
endfunction

"recalculate the tab warning flag when idle and after writing
autocmd cursorhold,bufwritepost * unlet! b:statusline_tab_warning

"return '[&et]' if &et is set wrong
"return '[mixed-indenting]' if spaces and tabs are used to indent
"return an empty string if everything is fine
function! StatuslineTabWarning()
    if !exists("b:statusline_tab_warning")
        let b:statusline_tab_warning = ''

        if !&modifiable
            return b:statusline_tab_warning
        endif

        let tabs = search('^\t', 'nw') != 0

        "find spaces that arent used as alignment in the first indent column
        let spaces = search('^ \{' . &ts . ',}[^\t]', 'nw') != 0

        if tabs && spaces
            let b:statusline_tab_warning = '[mixed-indenting]'
        elseif (spaces && !&et) || (tabs && &et)
            let b:statusline_tab_warning = '[&et]'
        endif
    endif
    return b:statusline_tab_warning
endfunction

"recalculate the long line warning when idle and after saving
autocmd cursorhold,bufwritepost * unlet! b:statusline_long_line_warning

"return a warning for "long lines" where "long" is either &textwidth or 80 (if
"no &textwidth is set)
"
"return '' if no long lines
"return '[#x,my,$z] if long lines are found, were x is the number of long
"lines, y is the median length of the long lines and z is the length of the
"longest line
function! StatuslineLongLineWarning()
    if !exists("b:statusline_long_line_warning")

        if !&modifiable
            let b:statusline_long_line_warning = ''
            return b:statusline_long_line_warning
        endif

        let long_line_lens = s:LongLines()

        if len(long_line_lens) > 0
            let b:statusline_long_line_warning = "[" .
                        \ '#' . len(long_line_lens) . "," .
                        \ 'm' . s:Median(long_line_lens) . "," .
                        \ '$' . max(long_line_lens) . "]"
        else
            let b:statusline_long_line_warning = ""
        endif
    endif
    return b:statusline_long_line_warning
endfunction

"return a list containing the lengths of the long lines in this buffer
function! s:LongLines()
    let threshold = (&tw ? &tw : 80)
    let spaces = repeat(" ", &ts)

    let long_line_lens = []

    let i = 1
    while i <= line("$")
        let len = strlen(substitute(getline(i), '\t', spaces, 'g'))
        if len > threshold
            call add(long_line_lens, len)
        endif
        let i += 1
    endwhile

    return long_line_lens
endfunction

"find the median of the given array of numbers
function! s:Median(nums)
    let nums = sort(a:nums)
    let l = len(nums)

    if l % 2 == 1
        let i = (l-1) / 2
        return nums[i]
    else
        return (nums[l/2] + nums[(l/2)-1]) / 2
    endif
endfunction


"statusline setup
set statusline=%f "tail of the filename

"display a warning if fileformat isnt unix
set statusline+=%#warningmsg#
set statusline+=%{&ff!='unix'?'['.&ff.']':''}
set statusline+=%*

"display a warning if file encoding isnt utf-8
set statusline+=%#warningmsg#
set statusline+=%{(&fenc!='utf-8'&&&fenc!='')?'['.&fenc.']':''}
set statusline+=%*

set statusline+=%h "help file flag
set statusline+=%y "filetype
set statusline+=%r "read only flag
set statusline+=%m "modified flag

"display a warning if &et is wrong, or we have mixed-indenting
set statusline+=%#error#
set statusline+=%{StatuslineTabWarning()}
set statusline+=%*

set statusline+=%{StatuslineTrailingSpaceWarning()}

set statusline+=%{StatuslineLongLineWarning()}

" set statusline+=%#warningmsg#
"set statusline+=%{SyntasticStatuslineFlag()}
" set statusline+=%*

"display a warning if &paste is set
set statusline+=%#error#
set statusline+=%{&paste?'[paste]':''}
set statusline+=%*

set statusline+=%= "left/right separator

function! SlSpace()
    if exists("*GetSpaceMovement")
        return "[" . GetSpaceMovement() . "]"
    else
        return ""
    endif
endfunc
set statusline+=%{SlSpace()}

set statusline+=%{StatuslineCurrentHighlight()}\ \ "current highlight
set statusline+=%c, "cursor column
set statusline+=%l/%L "cursor line/total lines
set statusline+=\ %P "percent through file
set laststatus=2
